package com.duojuhe.coremodule.help.service.impl;

import com.duojuhe.common.annotation.DataScopeFilter;
import com.duojuhe.common.bean.UserTokenInfoVo;
import com.duojuhe.common.constant.DataScopeConstants;
import com.duojuhe.common.enums.SystemEnum;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.duojuhe.common.utils.page.PageHelperUtil;
import com.duojuhe.coremodule.BaseService;
import com.duojuhe.coremodule.help.entity.HelpCategory;
import com.duojuhe.coremodule.help.entity.HelpInfo;
import com.duojuhe.coremodule.help.mapper.HelpCategoryMapper;
import com.duojuhe.coremodule.help.mapper.HelpInfoMapper;
import com.duojuhe.coremodule.help.pojo.dto.info.*;
import com.duojuhe.coremodule.help.service.HelpInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class HelpInfoServiceImpl extends BaseService implements HelpInfoService {
    @Resource
    private HelpCategoryMapper helpCategoryMapper;

    @Resource
    private HelpInfoMapper helpInfoMapper;

    /**
     * 【帮助详情】根据帮助发布ID获取帮助详情
     * @param req
     * @return
     */
    @Override
    public ServiceResult<QueryHelpInfoRes> queryHelpInfoResByInfoId(HelpInfoIdReq req) {
        QueryHelpInfoRes newsRes = helpInfoMapper.queryHelpInfoResByInfoId(req.getInfoId());
        if (newsRes==null || SystemEnum.IS_DELETE.YES.getKey().equals(newsRes.getIsDelete())){
            throw new DuoJuHeException(ErrorCodes.PARAM_ERROR);
        }
        return ServiceResult.ok(newsRes);
    }

    /**
     * 【分页查询帮助发布list】分页查询帮助发布list
     * @param req
     * @return
     */
    @DataScopeFilter
    @Override
    public ServiceResult<PageResult<List<QueryHelpInfoPageRes>>> queryHelpInfoPageResList(QueryHelpInfoPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, infoId desc");
        List<QueryHelpInfoPageRes> list = helpInfoMapper.queryHelpInfoPageResList(req,SystemEnum.IS_DELETE.NO.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【分页查询我发布的帮助list】分页查询我发布的帮助list
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryMyHelpInfoPageRes>>> queryMyHelpInfoPageResList(QueryMyHelpInfoPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, infoId desc");
        List<QueryMyHelpInfoPageRes> list = helpInfoMapper.queryMyHelpInfoPageResList(req,SystemEnum.IS_DELETE.NO.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }


    /**
     * 【分页查询我的回收站帮助list】分页查询我的回收站帮助list
     * @param req
     * @return
     */
    @DataScopeFilter(dataScope = DataScopeConstants.SELF_DATA)
    @Override
    public ServiceResult<PageResult<List<QueryMyHelpInfoPageRes>>> queryRecycleHelpInfoPageResList(QueryMyHelpInfoPageReq req) {
        PageHelperUtil.orderByAndStartPage(req, "sort desc,updateTime desc,createTime desc, infoId desc");
        List<QueryMyHelpInfoPageRes> list = helpInfoMapper.queryMyHelpInfoPageResList(req,SystemEnum.IS_DELETE.YES.getKey());
        return PageHelperUtil.returnServiceResult(req, list);
    }

    /**
     * 【保存】帮助发布帮助
     * @param req
     * @return
     */
    @Override
    public ServiceResult saveHelpInfo(SaveHelpInfoReq req) {
        //当前登录人
        UserTokenInfoVo userTokenInfoVo = getCurrentLoginUserInfoDTO();
        //检查分类
        checkInfoCategoryId(req.getCategoryId(),userTokenInfoVo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        //帮助id
        String infoId = UUIDUtils.getUUID32();
        //构建帮助对象
        HelpInfo helpInfo = new HelpInfo();
        helpInfo.setInfoId(infoId);
        helpInfo.setCategoryId(req.getCategoryId());
        helpInfo.setInfoTitle(req.getInfoTitle());
        helpInfo.setIntroduction(req.getIntroduction());
        helpInfo.setInfoContent(req.getInfoContent());
        helpInfo.setSort(req.getSort());
        helpInfo.setIsDelete(SystemEnum.IS_DELETE.NO.getKey());
        helpInfo.setCreateTime(nowDate);
        helpInfo.setCreateDeptId(userTokenInfoVo.getCreateDeptId());
        helpInfo.setCreateUserId(userTokenInfoVo.getUserId());
        helpInfo.setTenantId(userTokenInfoVo.getTenantId());
        helpInfo.setUpdateTime(nowDate);
        helpInfo.setUpdateUserId(userTokenInfoVo.getUserId());
        //设置允许查询权限
        helpInfo.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        helpInfoMapper.insertSelective(helpInfo);
        return ServiceResult.ok(infoId);
    }

    /**
     * 【修改】帮助发布帮助
     * @param req
     * @return
     */
    @Override
    public ServiceResult updateHelpInfo(UpdateHelpInfoReq req) {
        HelpInfo helpInfo = helpInfoMapper.selectByPrimaryKey(req.getInfoId());
        if (helpInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(helpInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //检查分类
        checkInfoCategoryId(req.getCategoryId(),helpInfo.getTenantId());
        //当前时间
        Date nowDate = new Date();
        HelpInfo updateHelpInfo = new HelpInfo();
        updateHelpInfo.setInfoId(helpInfo.getInfoId());
        updateHelpInfo.setCategoryId(req.getCategoryId());
        updateHelpInfo.setInfoTitle(req.getInfoTitle());
        updateHelpInfo.setIntroduction(req.getIntroduction());
        updateHelpInfo.setInfoContent(req.getInfoContent());
        updateHelpInfo.setSort(req.getSort());
        updateHelpInfo.setUpdateTime(nowDate);
        updateHelpInfo.setUpdateUserId(userId);
        //设置允许查询权限
        updateHelpInfo.setDataAllowAuth(SystemEnum.DATA_ALLOW_AUTH.ALL_AUTH.getKey());
        helpInfoMapper.updateByPrimaryKeySelective(updateHelpInfo);
        return ServiceResult.ok(req.getInfoId());
    }

    /**
     * 【彻底删除】根据帮助发布ID彻底删除帮助发布，注意一次仅能彻底删除一个帮助发布
     * @param req
     * @return
     */
    @Override
    public ServiceResult deleteHelpInfoByInfoId(HelpInfoIdReq req) {
        HelpInfo helpInfo = helpInfoMapper.selectByPrimaryKey(req.getInfoId());
        if (helpInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(helpInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //删除帮助
        helpInfoMapper.deleteByPrimaryKey(helpInfo.getInfoId());
        return ServiceResult.ok(helpInfo.getInfoId());
    }

    /**
     * 【回收站中】根据帮助发布ID把发布帮助放到回收站中
     * @param req
     * @return
     */
    @Override
    public ServiceResult putRecycleHelpInfoByInfoId(HelpInfoIdReq req) {
        HelpInfo helpInfo = helpInfoMapper.selectByPrimaryKey(req.getInfoId());
        if (helpInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(helpInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前时间
        Date nowDate = new Date();
        HelpInfo updateHelpInfo = new HelpInfo();
        updateHelpInfo.setInfoId(req.getInfoId());
        updateHelpInfo.setIsDelete(SystemEnum.IS_DELETE.YES.getKey());
        updateHelpInfo.setUpdateUserId(userId);
        updateHelpInfo.setDeleteTime(nowDate);
        updateHelpInfo.setUpdateTime(nowDate);
        helpInfoMapper.updateByPrimaryKeySelective(updateHelpInfo);
        return ServiceResult.ok(req.getInfoId());
    }

    /**
     * 【把回收站中的帮助恢复】根据帮助发布ID把回收站中的帮助恢复
     * @param req
     * @return
     */
    @Override
    public ServiceResult recoveryRecycleHelpInfoByInfoId(HelpInfoIdReq req) {
        HelpInfo helpInfo = helpInfoMapper.selectByPrimaryKey(req.getInfoId());
        if (helpInfo==null){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        //当前登录人
        String userId = getCurrentLoginUserId();
        if (!userId.equals(helpInfo.getCreateUserId())){
            return ServiceResult.fail(ErrorCodes.PARAM_ERROR);
        }
        HelpInfo updateHelpInfo = new HelpInfo();
        updateHelpInfo.setInfoId(req.getInfoId());
        updateHelpInfo.setUpdateTime(new Date());
        updateHelpInfo.setIsDelete(SystemEnum.IS_DELETE.NO.getKey());
        updateHelpInfo.setUpdateUserId(userId);
        helpInfoMapper.updateByPrimaryKeySelective(updateHelpInfo);
        return ServiceResult.ok(req.getInfoId());
    }

    /**
     * 【私有方法，辅助其他接口方法使用】 检查帮助分类是否存在
     */
    private void checkInfoCategoryId(String categoryId,String tenantId) {
        if (StringUtils.isBlank(categoryId)||StringUtils.isBlank(tenantId)){
            throw new DuoJuHeException(ErrorCodes.HELP_CATEGORY_NOT_EXIST);
        }
        HelpCategory helpCategory = helpCategoryMapper.selectByPrimaryKey(categoryId);
        if(helpCategory==null || !tenantId.equals(helpCategory.getTenantId())){
            throw new DuoJuHeException(ErrorCodes.HELP_CATEGORY_NOT_EXIST);
        }
    }
}
